<template>
	<scroll-view :scroll-y="true" class="Upload">
		<upload-item required title="分类" v-model="categoryIds" :selectorRange="categories" type="multiSelector" rangeKey="title"></upload-item>
		<upload-item required title="上传图片" type="imgUploader" :uploadImg.sync="bookImg"></upload-item>
		<view class="margin"></view>
		<template>
			<view class="bookInfo-form">
				<upload-item :type="['bookcatalog','gist'].includes(item.formName) ? 'textarea':'input'" :onlyRead="item.formName === 'isbn'"  :placeholder="item.placeholder" v-for="(item,index) in bookInfoList" :title="item.title" v-model="bookInfoForm[item.formName]" ></upload-item>
			</view>
		</template>
		<view class="margin"></view>
		<view v-for="(item,index) in bookReserves" :key="index" class="condition-form">
			<upload-item required title="品相" type="selector" :selectorRange="conditions" v-model="item.condition"></upload-item>
			<upload-item required title="位置" placeholder="请填写摆放位置" v-model="item.location"></upload-item>
			<upload-item required title="数量" placeholder="请填写摆放数量" v-model="item.storage"></upload-item>
			<upload-item title="折扣" placeholder="请填写折扣" v-model="item.discount"></upload-item>
			<view class="opertion-area" v-if="index === bookReserves.length - 1">
				<view @click="addFormItem">
					<!-- + 增加品相 -->
					+ 其他位置
				</view>
				<view v-if="index > 0" @click="deleteFormItem">
					- 取消摆放
				</view>
			</view>

		</view>
		<view class="bottom-wrapper">
			<button class="bottom-btn" @click="handleCancel">取消导入</button>
			<button class="bottom-btn confirm" @click="handleUpload">确认导入</button>
		</view>
	</scroll-view>
</template>

<script>
import uploadItem from './components/uploadItem.vue'

export default {
		components:{
			uploadItem
		},
		// computed:{
		// 	bookTitle(){
		// 		return '《' + this.inputText + '》'
		// 	}
		// },
		data() {
			return {
				errorText:'',
				categories:[],
				conditions:['中等','全新','良好','学霸'],
				categoryIds:'',
				// bookImg:'https://img.maimiaobook.com/cover/A26GR93187.jpg?x-oss-process=style/yuantu',
				bookImg:'',
				bookInfoForm:{},
				// conditionForms:[{
				// 	bookCondition:'',
				// 	discount:'0.53',
				// 	storage:'1'
				// }],
				bookReserves: [{
				    condition: '',
				    discount: '0.4',
				    location: '',
				    storage: '1'
				}],
				bookInfoList:[
					{
						title:'书名',
						formName:'title'
					},
					{
						title:'ISBN',
						formName:'isbn'
					},
					{
						title:'作者',
						formName:'author'
					},
					{
						title:'丛书信息',
						formName:'series'
					},
					{
						title:'出版社',
						formName:'publisher'
					},
					{
						title:'出版日期',
						formName:'pubdate'
					},
					{
						title:'出版地',
						formName:'pubplace'
					},
					{
						title:'装帧',
						formName:'binding'
					},
					{
						title:'中图分类号',
						formName:'genus'
					},
					{
						title:'纸张开数',
						formName:'format'
					},
					{
						title:'页数',
						formName:'page'
					},
					{
						title:'字数',
						formName:'wordnum'
					},
					{
						title:'版次',
						formName:'edition'
					},
					{
						title:'印次',
						formName:'yinci'
					},
					{
						title:'纸张类型',
						formName:'paper'
					},
					{
						title:'语言',
						formName:'language'
					},
					{
						title:'关键词',
						formName:'keyword'
					},
					{
						title:'目录',
						formName:'bookcatalog'
					},
					{
						title:'cip信息',
						formName:'cipText'
					},
					{
						title:'定价',
						formName:'price'
					},
					{
						title:'书本简介',
						formName:'gist',
						placeholder:'请输入书本简介'
					}
				]
			};
		},
		computed:{

		},
		watch:{
			errorText(v){
				if(v){
					uni.showToast({
						// mask:true,
						icon:'none',
						title:v,
						success: () => {
							this.errorText = ''
						}
					})
				}
			}
		},
		methods:{
			uniCloudUploadImage(){
			      return new Promise((resolve, reject) => {
			        uniCloud.uploadFile({
			          filePath: this.bookImg,
			          cloudPath: this.bookInfoForm.isbn + "." + this.bookImg.split('.')[1],
			          fileType:'image',
			          onUploadProgress:(progressEvent)=>{
			            console.log(progressEvent)
			            let percentCompleted = Math.round(
			                (progressEvent.loaded * 100) / progressEvent.total
			            )
			          },
			          success:(res)=>{
			            resolve(res)
			          },
			          fail:(err)=>{
			            reject(err)
			          }
			        })
			      })
			    },

			async handleUpload(){
				try{
					uni.showLoading({
						title:'请稍后'
					})
					const checkRes = await this.checkFormValid()
					if(checkRes.isValid){
						if (!this.isOnline(this.bookImg)) {
							const result = await this.uniCloudUploadImage()
							this.bookImg = result.fileID
							console.log('result',result)
						}

						await this.$api.collectBookInfo({
							...this.bookInfoForm,
							img:this.bookImg,
							subjectId:this.categoryIds.split('-')[1],
							subjectParentId:this.categoryIds.split('-')[0],
							bookReserves: this.bookReserves
						})

						uni.hideLoading();
						uni.showModal({
							title:'提示',
							content:'导入成功！',
							showCancel:false,
							success: () => {
								uni.navigateBack()
							}
						})
					}
				}catch(err){
					console.log(err);
					this.errorText = typeof err === 'object' ? err.message || err.errorText : err
				}

			},
			checkFormValid(){
				return new Promise((resolve,reject)=>{
					let checkRes = {
						isValid:false,
						errorText:''
					}

					function isValid(){
						checkRes.isValid = true
					}

					function isInvalid(str){
						checkRes.errorText = str
					}

					if(this.categoryIds.length === 0){
						isInvalid('请选择书本分类')
					}else if(this.bookImg.length === 0){
						isInvalid('请上传书本图片')
					}else if(this.bookReserves.some(item=>item.condition.length === 0 || item.storage.length === 0 || item.location.length === 0)){
						console.log(this.bookReserves);
						isInvalid('请填写品相相关必填字段')
					}else if(this.bookReserves.some(item=>!this.isDiscount(item.discount))){
						isInvalid('请填写合法的折扣类型')
					}else if(this.bookReserves.some(item=>!this.isStock(item.storage))){
						isInvalid('请填写合法的库存')
					}else{
						isValid()
						resolve(checkRes)
					}


					reject(checkRes)


				})
			},
			handleCancel(){
				uni.navigateBack()
			},

			isStock(stock){
				return /(^[1-9]{1}$)|(^[1-9]{1}\d+$)/.test(stock)
			},

			isDiscount(discount){
				return /^0.[1-9]\d?$/.test(discount)
			},

			isOnline(imgSrc){
				return /^http/.test(imgSrc)
			},

			addFormItem(){
				// this.conditionForms.length < this.conditions.length ? this.conditionForms.push({
				// 	bookCondition:'',
				// 	discount:'0.53',
				// 	storage:'1'
				// }) : this.errorText = '已添加所有品相'
				this.bookReserves.push({
					condition:'',
					discount:'0.4',
					storage:'1',
					location:''
				})
			},
			deleteFormItem(){
				this.bookReserves.pop()
			}
		},
		async created() {
			try{
        this.categories = await this.$api.getSubjectList()
			}catch(err){
				const networkStatus = await new Promise((resolve)=>{
					uni.getNetworkType({
						success: ({networkType}) => {
							resolve(networkType)
						}
					})
				})

				if(['none','unknown'].includes(networkStatus)){
					this.errorText = '连接失败，请检查网络连接'
				}else{
					this.errorText = '连接服务器错误，请联系管理员'
				}
			}

		},
		onLoad(options) {
			const bookInfo = JSON.parse(decodeURIComponent(options.bookInfo))
			this.bookInfoList.forEach(item => {
				this.bookInfoForm[item.formName] = bookInfo[item.formName] || '暂无信息'
			})
			this.bookImg = bookInfo.img
			console.log(this.bookInfoForm);
			console.log('img',this.bookImg);
		}
	}
</script>

<style lang="scss" scoped>
	.Upload{
		font-family: PingFangSC-Regular, sans-serif;
		background-color: #F2F2F2;
		width: 100vw;
		height: 100vh;
		padding-top: 10rpx;

		&::v-deep .UploadItem + .UploadItem{
			border-top: 2rpx solid #c8c7cc;

		}

		.margin{
			margin-top: 20rpx;
			// margin-bottom: 10rpx;
		}

		.condition-form{
			margin-bottom: 20rpx;
			// border: 1px solid black;
			.opertion-area{
				color: #1296db;
				margin: 10rpx 5% 0 5%;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			// .add{
			// 	margin: 10rpx 0 0 5%;
			// 	color: #1296db;
			// }
		}

		.bottom-wrapper{
			width: 100%;
			height: 120rpx;
			background-color: #F8F8F8;
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 20rpx 0 40rpx 0;
			margin-top: 40rpx;
			// padding-bottom: 40rpx;

			.bottom-btn{
				width: 310rpx;
				border: 3rpx solid #1296db;
				color: #1296db;
				font-family: PingFangSC-Medium, sans-serif;
				&::after{
					border: none;
				}

				&.confirm{
					color: white;
					background-color: #1296db;
				}
			}
		}
	}
</style>
